package com.example.demo1.controller;

import com.example.demo1.controller.requests.ModifyDrinkRequest;
import com.example.demo1.model.Drink;
import com.example.demo1.repository.DrinkRepository;
import com.example.demo1.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/drink")
public class DrinkController {
    @Autowired
    private IDrinkService drinkService;
    // get /drink
    @GetMapping("/")
    public List<Drink> getAll() {
        List<Drink> results = drinkService.getAllDrinks();

        // mock数据 - 后期使用数据库查询
//        ArrayList<Drink> results = new ArrayList<>();
//        results.add(Drink.builder().id(1).name("茉莉花茶").price(Money.parse("USD 23.87")).build());
//        results.add(Drink.builder().id(2).name("焦糖拿铁").price(Money.parse("USD 23.87")).build());
        return results;
    }
    // 日志
    // get /drink/4
    // path路径表示方法 id=4

    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable("id") Integer id) {
        log.info("查询饮品的id:{}", id);
        //后期使用数据库查询
        //select ... where id = $id
        Drink drink = Drink.builder().id(1).name("茉莉花茶").price(Money.parse("USD 23.87")).build();
        return drink;

    }

    //1. 直接使用model类接收用户参数
    //2. 编写一个TO类专门负责传值
    @PostMapping("/")
    public Drink addNewDrink(@RequestBody @Valid ModifyDrinkRequest drink,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        } else {
            log.info("创建新饮品:{}", drink);
            Drink saveddrink = new Drink();
            BeanUtils.copyProperties(drink,saveddrink);
            drinkService.addNewDrink(saveddrink,drink.getCategoryId());
            return saveddrink;
        }


    }

    //修改
    @PutMapping("/")
    public Drink modifyDrink(@RequestBody ModifyDrinkRequest request) {
        log.info("要修改的饮品:{}", request);
//        Drink updatedrink = Drink.builder().id(1).name("茉莉花茶").price(Money.parse("USD 23.87")).build();
        //通过id查找出饮品

        Drink drink = drinkService.getDrinkById(request.getId());
        BeanUtils.copyProperties(request,drink);
        drinkService.updateDrink(drink);
        return drink;
    }

    //删除
    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id) {
        log.info("要删除的饮品id:{}", id);
        drinkService.deleteDrinkById(id);
        return "删除成功";
    }

    //文件上传
    //前端类型必须设置为 multipart/form-data
    @PostMapping(value = "/upload",
            consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public String uploadFile(MultipartFile file) {
        String dest = "D:\\upload";
        String destFileName = dest + file.getOriginalFilename();
        File destFile = new File(destFileName);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功";
    }

        @PostMapping(value = "/batch",
                consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
        public List<Drink> uploadFiles(MultipartFile files) {
            List<Drink> results = new ArrayList<>();
            try {
//                InputStream inputStream = files.getInputStream();
//                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
//                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(
                                files.getInputStream()
                        )
                );
                String line = "";
                while ((line = reader.readLine())!=null){
                    String[] args = line.split(",");
                    Drink drink = Drink.builder().id(Integer.parseInt(args[0])).name(args[1]).price(Money.of(CurrencyUnit.of("CNY"),Double.parseDouble(args[2]))).build();
                    results.add(drink);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
                return results;
        }
    }



